package com.rpcLearning.transport.impl;

import com.rpcLearning.proto.Peer;
import com.rpcLearning.transport.TransportClient;
import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author:zyh
 * @Time:2021-03-17-18:22
 * @email:1269231889@qq.com
 */
public class HTTPClient implements TransportClient {
    private String url;

    @Override
    public void connect(Peer peer) {
        this.url = "http://" + peer.getHost() +
                ":" + peer.getPort();

    }

    //写入数据
    @Override
    public InputStream write(InputStream data) {
        try {
            HttpURLConnection url = (HttpURLConnection) new
                    URL(this.url).openConnection();
            url.setDoInput(true);
            url.setDoOutput(true);
            url.setUseCaches(true);
            url.setRequestMethod("POST");
            url.connect();

            IOUtils.copy(data, url.getOutputStream());
            int responseCode = url.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                return url.getInputStream();
            } else {
                return url.getErrorStream();
            }
        } catch (IOException e) {
            throw new IllegalStateException(e);
        }
    }

    //基于http为短链接，所以可以不用close端口
    @Override
    public void close() {

    }
}
